﻿using Newtonsoft.Json;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ec_System.API
{
    public static class RedisHelper
    {


        public static T Get<T>(string key)
        {
            using (IRedisClient redisClient = RedisManager.GetClient(true))//new RedisClient(RedisHost, RedisPort))
            {
                try
                {
                    var result = redisClient.Get<string>(key);
                    if (result == null)
                        return default(T);
                    else
                        return JsonConvert.DeserializeObject<T>(result);
                }
                catch (Exception)
                {
                    return default(T);
                }
            }
        }
        public static bool Set<T>(string key, T value, int minutes)
        {
            using (IRedisClient redisClient = RedisManager.GetClient(false))//new RedisClient(RedisHost, RedisPort))
            {
                if (minutes == -1)
                {
                    return redisClient.Set<string>(key, JsonConvert.SerializeObject(value));
                }
                else
                {
                    return redisClient.Set<string>(key, JsonConvert.SerializeObject(value), DateTime.Now.AddMinutes(minutes));
                }
            }
        }
        public static void Delete<T>(string key)
        {
            using (IRedisClient redisClient = RedisManager.GetClient(false))
            {
                redisClient.Remove(key);
            }
        }
    }
}
